//import  'https://unpkg.com/vue@2.7.14/dist/vue.js';
import './vue.js'
//import  "https://unpkg.com/axios@1.3.1/dist/axios.min.js"
import './axios.min.js'
// https://autumnfish.cn
axios.defaults.baseURL = 'https://autumnfish.cn';

class Music {

    url = ''
    #data = {}
    #name = ""
    #artists = []
    #artistsShow = ""
    #duration = 0
    #durationShow = "00:00"
    #showName = ""
    #isLocal = false

    constructor(data) {
        if (typeof data !== 'undefined') {
            if (data instanceof File) {
                this.#isLocal = true
                this.#data = data
                let names = data.name.replaceAll(".mp3", '').split("-");
                this.#artistsShow = names[0].trim()
                this.#name = names[1].trim();
                this.url = URL.createObjectURL(data);
            } else {
                this.#data = data
                this.#name = data.name;
                this.#artists = data.artists
                this.#duration = data.duration
            }
        } else {
            this.#name = ""
            this.#artistsShow = ""
            this.#duration = 0
            this.#artists = []
            this.url = ""
            this.#isLocal = true
        }
    }

    get Name() {
        return this.#name
    }

    getUrl() {
        if (!this.#isLocal && this.url === "") {
            axios.get('/song/url?id=' + this.#data.id).then((res) => {
                    this.url = res.data.data[0].url;
                }
            )
        }
    }


    get Artists() {
        if (!this.#artistsShow) {
            this.#artistsShow = this.#artists.flatMap(i => i.name).join('、')
        }
        return this.#artistsShow
    }

    get Duration() {
        let duration = this.#duration / 1000
        let mm = Math.trunc(duration / 60)
        let ss = Math.trunc(duration % 60)
        this.#durationShow = ((Array(2).join('0') + mm).slice(-2)) + ':' + ((Array(2).join("0") + ss).slice(-2));
        return this.#durationShow
    }

    set Duration(duration) {
        this.#duration = duration
    }

    get ShowName() {
        if (!this.#showName) {
            this.#showName = `${this.Name} - ${this.Artists}`
        }
        return this.#showName
    }

    get IsLocal() {
        return this.#isLocal
    }

    get Data() {
        return this.#data
    }
}


const vue = new Vue({
    el: "#app",
    data: {
        // 搜索关键字
        query: '',
        // 歌曲列表
        musicList: [],
        // 歌曲url
        musicUrl: '',
        // 是否正在播放
        isPlay: false,
        // 歌曲封面地址
        coverUrl: '',
        //储存当前播放歌曲的索引
        currentIndex: -1,
        //是否展示专辑封面
        isAlbumDisplay: false,
        //播放器音量
        volume: 100,
        // 当前已经播放的时间
        currentTime: 0,
        // 音乐总时长
        totalTime: 0,
        // 定时器
        timer: null,
        // 当前播放的音乐
        currentMusic: new Music(),
        // 当前歌曲歌词
        currentMusicLyrics: [],
        // 当前歌曲当前播放时间的歌词
        musicLyricIndex: 0,
        // 播放模式 1：列表循环,2:单曲循环
        playMode: 2,
    },
    methods: {
        // 搜索歌曲
        searchMusic() {
            if (this.query === "") {
                return
            }
            axios.get('/search?keywords=' + this.query).then(response => {
                // 保存内容
                response.data.result.songs.flatMap(i => this.musicList.push(new Music(i)));
            })
            // 清空搜索
            this.query = ''
            //
            this.currentIndex = -1
            this.currentMusic = new Music()
        },
        // 播放歌曲
        playMusic(index) {

            if (this.currentIndex !== index) {
                //设置当前播放歌曲索引
                this.currentIndex = index;
                // 清除之前的进度条计时器
                clearInterval(this.timer)

                this.currentMusic = this.musicList[index]

                this.currentMusic.getUrl()
                this.$refs.myAudio.play();

            } else {
                if (this.isPlay) {
                    this.$refs.myAudio.pause();
                } else {
                    this.$refs.myAudio.play();
                }
            }


            /*  //歌词解析即后续操作
              this.musicLyricIndex = 0;
              this.$refs.lyricsDisplay.style.top = `${98 - 38 * this.musicLyricIndex}px`
              // 获取歌词
              //this.getCurrentMusicLyric(this.musicList[index].Data.id)*/


        },
        getCurrentMusicLyric(musicId) {
            axios.get('/lyric?id=' + musicId).then(response => {
                // 保存歌曲url地址
                let lyric = response.data.lrc.lyric

                let lyrics = lyric.split("\n")
                let musicLyric = []
                lyrics.forEach((value) => {
                    let parsePattern = /\[(\d+):(\d+)\.(\d*)]/g
                    let regExpMatchArray = parsePattern.exec(value)
                    let lyric = value.replace(parsePattern, '')
                    if (regExpMatchArray != null && lyric.trim() !== "") {
                        let minute = Number.parseInt(regExpMatchArray[1])
                        let second = Number.parseInt(regExpMatchArray[2])
                        let millisecond = Number.parseInt(regExpMatchArray[3])
                        let time = minute * 60 + second + millisecond / 1000;
                        musicLyric.push({
                            "time": time,
                            "lyric": lyric
                        })
                    }
                })
                this.currentMusicLyrics = musicLyric
            })
        },
        // audio的play事件
        playOrPause() {

            //判断musicList是否有数据，防止无效播放
            if (this.currentIndex < 0 || this.currentIndex >= this.musicList.length) {
                return
            }

            // 如果正在播放则暂停
            if (this.isPlay) {
                this.$refs.myAudio.pause();
            } else {
                if (this.currentMusic.url === "") {
                    this.currentMusic.getUrl()
                } else {
                    this.$refs.myAudio.play();
                }

            }

        },
        nextSong() {
            this.currentIndex++;
            if (this.currentIndex >= this.musicList.length) {
                this.currentIndex = 0
            }
            this.currentMusic = this.musicList[this.currentIndex]
            this.playOrPause()
        },
        preSong() {
            if (this.currentIndex > 0) {
                this.currentIndex--
            } else {
                this.currentIndex = this.musicList.length - 1
            }
            this.currentMusic = this.musicList[this.currentIndex]
            this.playOrPause()
        },
        displayAlbum() {
            this.isAlbumDisplay = !this.isAlbumDisplay
        },
        onPlay() {
            this.isPlay = true
            this.currentTime = this.$refs.myAudio.currentTime;
            let _this = this
            this.timer = setInterval(function () {
                _this.currentTime = _this.$refs.myAudio.currentTime;
                _this.$refs.musicProgress.style.width = (_this.currentTime / _this.totalTime) * 100 + "%"

                if (_this.currentMusicLyrics.length !== 0 && _this.musicLyricIndex < _this.currentMusicLyrics.length) {
                    if (_this.$refs.myAudio.currentTime > _this.currentMusicLyrics[_this.musicLyricIndex].time) {
                        _this.$refs.lyricsDisplay.style.top = `${98 - 38 * _this.musicLyricIndex}px`
                        _this.musicLyricIndex++;
                    }
                }


            }, 50)
        },
        onPause() {
            this.isPlay = false
            clearInterval(this.timer)
        },
        onCanplay() {
            this.totalTime = this.$refs.myAudio.duration
            this.currentMusic.Duration = this.$refs.myAudio.duration * 1000

        },
        openFile() {
            const files = this.$refs.musicFiles.files;
            if (files.length === 0) {
                console.log("没有文件被选中")
                return
            }
            // 解析文件
            for (let i = 0; i < files.length; i++) {
                this.musicList.push(new Music(files[i]))
            }
        }, onEndPlay() {
            this.isPlay = false
            this.$refs.myAudio.loop = false
            switch (this.playMode) {
                case 1:
                    this.nextSong()
                    break
                case 2:
                    this.$refs.myAudio.play()
                    break
                case 3:
                    break

                default:
                    console.log("错误的播放模式，停止播放！！！")
                    break
            }
        },
        durationConvert(time, step = 1000) {
            let duration = time / step
            let mm = Math.trunc(duration / 60)
            let ss = Math.trunc(duration % 60)
            return ((Array(2).join('0') + mm).slice(-2)) + ':' + ((Array(2).join("0") + ss).slice(-2));
        }
    },
});


//获得边界盒子元素，用于获取边界
function getRangeBox(_this) {
    return _this.parentElement.parentElement;
}

function getCoefficient(event, slider) {
    let rect = slider.getBoundingClientRect()
    let K
    let height = slider.clientHeight
    let clientY
    if (typeof (TouchEvent) != "undefined" && event instanceof TouchEvent) {
        clientY = event.touches[0].clientY
    } else {
        clientY = event.clientY
    }
    const offsetY = clientY - rect.top
    K = 1 - offsetY / height
    return K > 0 ? (K > 1 ? 1 : K) : 0
}

const volumeThumb = document.getElementById("volume-thumb")
const volumeSlider = document.getElementById("volume-slider")
const volumeProgressWrap = document.getElementById("volume-progress-wrap")
const myAudio = document.getElementById("myAudio")
const playBtn = document.getElementById("playBtn")
const canvas = document.getElementById("canvas")
const canvasContext = canvas.getContext("2d")
volumeThumb.onmousedown = function (event) {
    const slider = getRangeBox(this);
    volumeProgressWrap.onmousemove = function (event) {

        const volume = Math.round(getCoefficient(event, slider) * 100)
        volumeSlider.style.height = volume + '%'
        document.querySelector('#myAudio').volume = volume / 100
        vue.volume = volume;

        //防止选择内容--当拖动鼠标过快时候，弹起鼠标，bar也会移动，修复bug
        window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty()
    }

}
volumeProgressWrap.onmouseup = function () {
    //弹起鼠标不做任何操作
    volumeProgressWrap.onmousemove = null
}
// onmouseleave 不支持事件冒泡
volumeProgressWrap.onmouseleave = function () {
    volumeProgressWrap.onmousemove = null
}
myAudio.onplay = function () {
    // 设置播放图标样式
    playBtn.getElementsByTagName('iconpark-icon')[0].name = 'pause'

}
myAudio.onpause = function () {
    // 设置播放图标样式
    playBtn.getElementsByTagName('iconpark-icon')[0].name = 'play-one'
}

// 绘制准备阶段

const canvasWidth = canvas.width
const canvasHeight = canvas.height - 3


const barWidth = 1

function animation(dataArray, bufferLength) {
    let x = 0;
    if (vue.$data.isPlay) {
        canvasContext.clearRect(0, 0, canvasWidth, canvasWidth)
        for (let i = 0; i < bufferLength; i++) {
            let barHeight = (1 - (dataArray[i] / 255)) * canvasHeight;
            canvasContext.fillStyle = 'rgb(255,255,255)'
            if (i === 0) {
                canvasContext.fillRect(canvasWidth / 2, canvasHeight - barHeight, barWidth, barHeight)
            } else {
                canvasContext.fillRect(canvasWidth / 2 + x, canvasHeight - barHeight, barWidth, barHeight)
                canvasContext.fillRect(canvasWidth / 2 - x, canvasHeight - barHeight, barWidth, barHeight)
            }


            x += barWidth + 2;
        }
    }
}

class AudioVisualization {
    constructor(audio, animation) {
        this.audio = audio;
        this.animation = animation;
        this.fftSize = 64;
    }

    openPlay() {
        let self = this;
        let a = this.audio;

        //储存定时器
        let timer = null;

        //解析器
        let AudCtx = new AudioContext();
        let src = AudCtx.createMediaElementSource(a);
        let analyser = AudCtx.createAnalyser();

        src.connect(analyser);
        analyser.connect(AudCtx.destination);
        //analyser.fftSize = this.fftSize;

        let bufferLength
        // 让bufferLength = fftSize
        // bufferLength = analyser.frequencyBinCount;
        // 通过控制数字大小来控制每次取出数据，进而控制线条数量

        bufferLength = 45

        let dataArray = new Uint8Array(bufferLength);

        function changeTime() {
            analyser.getByteFrequencyData(dataArray);
            self.animation(dataArray, bufferLength);
            // 进行下帧渲染
            timer = requestAnimationFrame(changeTime);
        }

        a.addEventListener('play', () => {
            changeTime();
        })

        a.addEventListener('pause', () => {
            cancelAnimationFrame(timer);
        })
    }
}


let audioVisualization = new AudioVisualization(myAudio, animation);
audioVisualization.openPlay()

function getRandomArbitrary(min, max) {
    return Math.random() * (max - min) + min;
}
